package com.javaex.book.dao.impl;

import java.math.BigDecimal;
import java.util.List;

import com.javaex.book.dao.BookDao;
import com.javaex.book.pojo.Book;
import com.javaex.book.utils.Pagination;

public class BookDaoImpl extends BaseDao implements BookDao {

	@Override
	public Integer addBook(Book book) {
		String sql = "INSERT INTO books(name, author, price, sales, stock, imgPath) values(?, ? , ?, ?, ?, ?)";
		return execute(sql, book);
	}

	@Override
	public Integer deleteBookById(Integer id) {
		String sql = "DELETE FROM books WHERE id = ?";
		return execute(sql, new Object[] { id });
	}

	@Override
	public Integer updateBook(Book book) {
		String sql = "UPDATE books SET name = ?, author = ?, price = ?, sales = ?, stock = ?, imgPath = ? WHERE id = ?";
		return execute(sql, book);
	}

	@Override
	public Book queryBookById(Integer id) {
		String sql = "SELECT id, name, author, price, sales, stock, imgPath FROM books WHERE id = ?";
		return findOne(sql, Book.class, new Object[] { id });
	}

	@Override
	public List<Book> queryBookList(Pagination pagination, BigDecimal minPrice, BigDecimal maxPrice) {
		if (minPrice != null && maxPrice != null && minPrice.compareTo(new BigDecimal(0)) > -1 && maxPrice.compareTo(minPrice) > -1) {
			String sql = "SELECT id, name, author, price, sales, stock, imgPath FROM books WHERE price >= ? AND price <= ? ORDER BY id limit ?, ?";
			return findMany(sql.toString(), Book.class, new Object[] { minPrice, maxPrice, pagination.getStart(), pagination.getSize() });
		}
		String sql = "SELECT id, name, author, price, sales, stock, imgPath FROM books limit ?, ?";
		return findMany(sql.toString(), Book.class, new Object[] { pagination.getStart(), pagination.getSize() });
	}

	@Override
	public Integer countBooks(BigDecimal minPrice, BigDecimal maxPrice) {
		if (minPrice != null && maxPrice != null && minPrice.compareTo(new BigDecimal(0)) > -1 && maxPrice.compareTo(minPrice) > -1) {
			String sql = "SELECT COUNT(*) FROM books WHERE price >= ? AND price <= ?";
			return count(sql, new Object[] { minPrice, maxPrice });
		}
		String sql = "SELECT COUNT(*) FROM books";
		return count(sql, null);
	}

}
